package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;


    /**
     * 管理员页面订单明细
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Page<OrdersDto> findPage(int page, int pageSize, String number, String beginTime, String endTime) {
        log.info("page={},pageSize={}",page,pageSize);
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> pageDto = new Page<>();
        //创建条件构造器""
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件，根据number进行like模糊查询
        queryWrapper.like(!StringUtils.isEmpty(number),Orders::getNumber,number);
        //根据DateTime进行时间范围查询
        if(beginTime != null && endTime !=null){
            queryWrapper.ge(Orders::getOrderTime,beginTime);//ge: 大于等于>=
            queryWrapper.le(Orders::getOrderTime,endTime);//le: 小于等于<=
        }

        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //进行分页查询
        orderMapper.selectPage(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,pageDto,"records");

        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);

            //此处相当于是给userName 赋值 consignee_userId
            String consignee = item.getConsignee();
            String name = consignee;
            ordersDto.setUserName(name);

            return ordersDto;
        }).collect(Collectors.toList());

        pageDto.setRecords(list);
        return pageDto;
    }

    @Override
    public void submit(Orders orders,User user) {

        orders.setNumber(IdWorker.getId() +"");
        orders.setStatus(2);//订单状态：1待付款 2待派送 3已派送 4已完成 5已取消
        orders.setUserId(user.getId());//设置用户id
        orders.setOrderTime(LocalDateTime.now());//设置付款时间
        orders.setCheckoutTime(LocalDateTime.now());
        //付款方式 总金额 备注 不需要设置，因为页面已经提供了
        orders.setUserName(user.getName());//提交订单的用户用户名
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());//收获人的电话
        orders.setAddress(
                (addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "")+
                        (addressBook.getCityName() != null ? addressBook.getCityName() : "")+
                        (addressBook.getDistrictName() !=null ? addressBook.getDistrictName() : "")+
                        (addressBook.getDetail() != null ? addressBook.getDetail() : "")
        );//收货人的地址 = 省份 + 城市 + 详细地址

        orders.setConsignee(addressBook.getConsignee());//收货人名字
        orderMapper.insert(orders);//在订单表添加订单
        List<ShoppingCart> cartList = shoppingCartService.list();//先从购物车里面拿出数据，再往订单详情表添加数据
        for(ShoppingCart cart : cartList){//遍历购物车的数据，每一条购物车数据就是一个订单详情对象
            OrderDetail orderDetail = new OrderDetail();//遍历一次购物车对象，就创建一个订单详情对象
            BeanUtils.copyProperties(cart,orderDetail);//把购物车条目对象拷贝到订单详情对象身上
            orderDetail.setOrderId(orders.getId());//设置属于哪个订单
            orderDetailService.add(orderDetail);//添加到订单详情表即可
            shoppingCartService.clean();//订单都已经添加好了，那么就清空购物车
        }
    }

    /**
     * 移动端页面订单查询
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<OrdersDto> userPage(int page, int pageSize) {
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        Page<OrdersDto> pageDto = new Page<>();
        //创建条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        //添加排序条件，根据更新时间降序排序
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //进行分页查询
        orderMapper.selectPage(pageInfo,queryWrapper);

        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();

        BeanUtils.copyProperties(pageInfo,pageDto,"records");
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);

            Long orderId = item.getId();

            wrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetails = orderDetailService.getByOrderId(orderId);
            //BeanUtils.copyProperties(item,ordersDto);
            if(orderDetails != null){
                ordersDto.setOrderDetails(orderDetails);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        pageDto.setRecords(list);
        return pageDto;
    }

//    @Override
//    public void update(Orders orders) {
//
//        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(Orders::getId,orders.getId());
//        updateWrapper.set(Orders::getStatus,orders.getStatus());//3
////        updateWrapper.set(Orders::getStatus,4);
//        //orderService.update(orders);
////        updateWrapper.
//
//    }


}
